package com.leetcode.根据数据结构分类.数组;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: xiaomi
 * @date: 2021/1/10
 * @description: 228. 汇总区间
 * https://leetcode-cn.com/problems/summary-ranges/
 */
public class A_228_汇总区间 {

	/**
	 * O(n)
	 * @param nums
	 * @return
	 */
	public List<String> summaryRanges(int[] nums) {
		List<String> res = new ArrayList<>();
		if (nums == null || nums.length == 0) {
			return res;
		}

		int begin = 0;
		//进行遍历
		for (int i = 1, end = begin; i < nums.length; ) {

			while (i < nums.length && nums[end] + 1 == nums[i]) {
				end = i++;
			}

			//此时 end到达符合要求的位置
			if (begin == end) {
				res.add(nums[begin] + "");
			} else {
				res.add(nums[begin] + "->" + nums[end]);
			}
			begin = end = i++;
		}
		//如果最后一个
		if (begin == nums.length - 1) {
			res.add(nums[begin] + "");
		}

		return res;
	}


	public static void main(String[] args) {
		int[] nums = new int[]{0, 1, 2, 4, 5, 7};
		nums = new int[]{0, 1, 2, 4, 5, 6};
		nums = new int[]{0, 2, 3, 4, 6, 8, 9};
		final A_228_汇总区间 action = new A_228_汇总区间();
		final List<String> res = action.summaryRanges(nums);
		System.out.println("res = " + res);
	}
}
